Page({
  data: {
    form: {
      name: '',
      amount: '',
      unit: '',
      calorie: '',
      calorieUnit: 'kcal', // kcal 千卡 / kj 千焦
      image: '',
      protein: '',
      fat: '',
      carb: '',
      fiber: '',
      sodium: ''
    }
  },
  onInput(e) {
    const key = e.currentTarget.dataset.key;
    const value = e.detail.value;
    this.setData({ [`form.${key}`]: value });
  },
  onSwitchUnit(e) {
    const unit = e.currentTarget.dataset.unit;
    this.setData({ 'form.calorieUnit': unit });
  },
  onChooseImage() {
    wx.chooseMedia({
      count: 1,
      mediaType: ['image'],
      success: (res) => {
        const filePath = res.tempFiles && res.tempFiles[0] ? res.tempFiles[0].tempFilePath : '';
        this.setData({ 'form.image': filePath });
      }
    });
  },
  onSave() {
    const f = this.data.form;
    if (!f.name) {
      wx.showToast({ title: '请填写食物名称', icon: 'none' });
      return;
    }
    // 存储到本地，供 meal 页面使用（示例）
    const list = wx.getStorageSync('customFoods') || [];
    list.push({ ...f, id: Date.now() });
    wx.setStorageSync('customFoods', list);
    wx.showToast({ title: '已保存', icon: 'success' });
    setTimeout(() => wx.navigateBack(), 400);
  }
});


